package com.study.elasticsearch.clientHighLevelClient;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.PutMappingRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class ServiceImpl {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    public List<Hotel> queryList(RequestParams requestParams){
        List<Hotel> result =new ArrayList<>();
        String indexName = "order_cbm";
        SearchRequest searchRequest = new SearchRequest(indexName);
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("policyNo", "123");
        boolQueryBuilder.must(termQueryBuilder);
        TermQueryBuilder tb = QueryBuilders.termQuery("orderType", "1235");
        boolQueryBuilder.must(tb);

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(boolQueryBuilder);
        int page = 0;
        int pageSize = 2;
        int total = 0;
        try {
            while(true){
                searchSourceBuilder.from(page);
                searchSourceBuilder.size(pageSize);
                searchRequest.source(searchSourceBuilder);
                SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
                System.out.println("查询结果："+searchRequest.toString());

                SearchHits hits = search.getHits();
                SearchHit[] hits1 = hits.getHits();

                if(hits1 == null || hits1.length == 0){
                    break;
                }
                for (SearchHit documentFields : hits1) {
                    JSONObject jsonObject = JSONUtil.parseObj(documentFields);
                    System.out.println(jsonObject);
                }
                page += pageSize;
                total += hits1.length;
     /*           Optional<SearchHit[]> searchHits = Optional.ofNullable(search)
                        .map(SearchResponse::getHits)
                        .map(SearchHits::getHits);
                SearchHit[] searchHits1 = searchHits.get();
                for (SearchHit documentFields : searchHits1) {
                    String sourceAsString = documentFields.getSourceAsString();
                    Hotel document = JSON.parseObject(sourceAsString, Hotel.class);
                    System.out.println(document.toString());
                    result.add(document);
                }*/
            }
            System.out.println("总数："+total);

            /*
               Optional.ofNullable(search).map(SearchResponse::getHits)
                    .map(SearchHits::getHits)
                    .map(hit->Document document = JSON.parseObject(hit.getSourceAsString(),ParseContext.Document.class));
            */

        }catch (Exception e){
            System.out.println(e);
        }
        System.out.println(total);
        return result;

    }

    public AcknowledgedResponse update()throws Exception{
        String newFieldMapping = "{\n" +
                "  \"properties\": {\n" +
                "    \"father\": {\n" +  // 新字段名称
                "      \"type\": \"text\"\n" +  // 新字段类型
                "    }\n" +
                "  }\n" +
                "}";
        PutMappingRequest putMappingRequest = new PutMappingRequest("my_st2");
        putMappingRequest.source(newFieldMapping, XContentType.JSON);
        AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().putMapping(putMappingRequest, RequestOptions.DEFAULT);
        return acknowledgedResponse;
    }

    public UpdateResponse updateData()throws Exception{
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("age", 320);
        UpdateRequest request = new UpdateRequest("my_st","1").doc(jsonMap);
        UpdateResponse update = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        return update;
    }
}
